package com.umakr.ax.common.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.umakr.ax.common.enm.AttentionFrom;
import com.umakr.ax.common.mapper.PluginCouponResultMapper;
import com.umakr.ax.common.model.PluginCoupon;
import com.umakr.ax.common.model.PluginCouponResult;
import com.umakr.ax.common.vo.PluginCouponListVO;
import com.umakr.ax.common.vo.PluginCouponResultListVO;
import com.umakr.ax.core.base.BaseService;
import com.umakr.ax.utils.CacheUtil;
import com.umakr.ax.utils.FormatPhotoUrlUtil;
import com.umakr.ax.utils.RandomCharDataUtil;
import com.umakr.ax.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * <p>
 * ${table.comment} 服务实现类
 * </p>
 *
 * @author Umakr-Code-Generator
 * @since 2017-12-30
 */
@Service
public class PluginCouponResultService extends BaseService<PluginCouponResultMapper, PluginCouponResult>{
    @Autowired
    PluginCouponService pluginCouponService;
    @Autowired
    RadioStationFollowerService radioStationFollowerService;
    @Autowired
    Environment env;
    Semaphore semaphore = new Semaphore(1,true);

    private static final String OSS_IMG_PATH = "oss.img.path";
    private static final String VALUE = "value";
    private static final String COUPON_GET = "coupon.get.";
    private static final String COUPON_ID = "couponid";
    private static final String COUPON_GETTER_COUNT = "coupon.getterCount.";
    private static final String USESTATUS_NAME = "useStatusName";
    private static final String USESTATUS_COLOR = "useStatusColor";
    private static final String HEADIMG_URL = "headImgUrl";


    public Object listCouponsByCouponId(Long couponId,Integer status){

        Page<PluginCouponResultListVO> page = baseMapper.listCouponsByCouponId(couponId,status);

        formatPlugCoupon(page);

        List<Integer> countMap = baseMapper.countCouponsResultByCouponId(couponId);
        WebUtil.addParamToPage(page,"gettedCount",countMap.get(0));
        WebUtil.addParamToPage(page,"usedCount",countMap.get(1));

        return page;
    }

    public Object listCouponsByUserIdAndStatus(Long userId,Integer status){
        String aliUrl = env.getProperty(OSS_IMG_PATH);
        PluginCouponResult pcr = new PluginCouponResult();
        Page<PluginCouponListVO> page = baseMapper.listCouponsByUserIdAndStatus(userId, status);
        Date currentDate = new Date();
        for(PluginCouponListVO vo : page.getRecords()){
            //判断是否过期
            if(currentDate.getTime() <= vo.getEndTime().getTime()){
                if(vo.getStatus() == 0){
                    vo.setStatusName("未使用");
                }else if(vo.getStatus() == 1){
                    vo.setStatusName("已使用");
                }else if(vo.getStatus() == 2){
                    vo.setStatusName("已过期");
                }
            } else {
                if(vo.getStatus() != 1) {
                    vo.setStatusName("已过期");
                    pcr.setUseStatus(2);
                    pcr.setId(vo.getId());
                    update(pcr);
                } else {
                    vo.setStatusName("已使用");
                }
            }

            if(vo.getSellerLogo() != null) {
                vo.setSellerLogo(aliUrl+vo.getSellerLogo());}
        }

        return page;
    }

    public Object deleteOneCouponById(Long id ){
        int code = 0;
        String msg ;

        PluginCouponResult result = queryById(id);
        //result.
        //修改状态 暂时没有这个字段
        result.setDelStatus(1);
        update(result);
        code = 1;
        msg = "删除成功";
        return resultMap(code,msg);
    }

    public Object checkCouponByCheckNum(Long checkUserId,String checkNum ){
        int code = 1;
        String msg = "";

        Date currentDate = new Date();

        //TODO 需要解析二维码信息 暂时没有解析或者解密
        EntityWrapper<PluginCouponResult> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("coupon_num",checkNum);
        entityWrapper.eq("del_status",0);
        PluginCouponResult pcr =  selectOne(entityWrapper);
        if(pcr != null){
            PluginCoupon  pc = pluginCouponService.queryById(pcr.getCouponid());
            if(pc != null){
                //判断活动是否未开始或过期
                if(pc.getRpcStarttime().getTime() > currentDate.getTime() ){
                    pcr.setCheckTime(currentDate);
                    pcr.setCheckUserId(checkUserId);
                    pcr.setUseStatus(1);
                    msg = "未到使用时间";
                } else if(currentDate.getTime() <= pc.getRpcEndtime().getTime()){
                    pcr.setCheckTime(currentDate);
                    pcr.setCheckUserId(checkUserId);
                    pcr.setUseStatus(1);
                    msg = "优惠券验证成功";
                }else{
                    pcr.setUseStatus(2);
                    code = 0;
                    msg = "优惠券已过期";
                }
                update(pcr);
            }else{
                code = 0;
                msg = "未找到相关的优惠券";
            }
        }else{
            code = 0;
            msg = "未找到相关的优惠券或已被删除";
        }
        return resultMap(code,msg);
    }

    public Object saveCouponResult(Long couponId,Long userId){

        int code = 1;
        String msg = "请求已发送";

        Date currentDate = new Date();

        try {
            //请求占用一个资源
            semaphore.acquire(1);
            Map<String,Object> getMap = Maps.newHashMap();
            getMap.put("key",0);
            getMap.put("text","排队抢券中");
            getMap.put(VALUE,"目前排队人数过多，正在排队抢券中，请稍后");
            CacheUtil.getCache().setKeyValue(COUPON_GET + couponId + "." + userId, getMap);

            PluginCoupon pc = pluginCouponService.queryById(couponId);
            int maxCount = pc.getRpcMaxCount();
            int perCount = pc.getRpcCouLimit();

            EntityWrapper<PluginCouponResult> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq(COUPON_ID, couponId);
            entityWrapper.eq("userid", userId);
            List<PluginCouponResult> pcrList = selectList(entityWrapper);
            if (perCount > pcrList.size()) {
                PluginCouponResult pcr = new PluginCouponResult();

                //获取优惠券使用个数
                Object getterCountObj = CacheUtil.getCache().get(COUPON_GETTER_COUNT + couponId);
                int getterCount = 0;
                if (getterCountObj != null) {
                    getterCount = (int) getterCountObj;
                }

                if (getterCount <= maxCount) {
                    pcr.setUseStatus(0);
                    pcr.setCouponid(couponId);
                    pcr.setGetTime(currentDate);
                    pcr.setUserid(userId);
                    pcr.setCouponNum(RandomCharDataUtil.createRandomCharData(20));
                    update(pcr);

                    if(perCount == pcrList.size()+1) {
                        //领取成功，但是已达到领取上限，之后不可继续领取
                        getMap.put("key", -3);
                        getMap.put("text","您已获取该优惠券");
                    }else{
                        //领取成功，但是未达到领取上限，还可继续领取
                        getMap.put("key", 1);
                        getMap.put("text","领取卡券");
                    }
                    radioStationFollowerService.autoAttention(userId,pc.getRsId(), AttentionFrom.SHAKE);
                    getMap.put(VALUE, "恭喜您，抢券成功");
                    CacheUtil.getCache().setKeyValue(COUPON_GET + couponId + "." + userId, getMap);

                    getterCount++;
                    CacheUtil.getCache().setKeyValue(COUPON_GETTER_COUNT + couponId, getterCount);
                }else{
                    getMap.put("key",-2);
                    getMap.put("text","活动结束");
                    getMap.put(VALUE,"对不起，优惠券已被抢完，没有更多优惠券了！");
                    CacheUtil.getCache().setKeyValue(COUPON_GET + couponId + "." + userId, getMap);
                }
            }else{
                getMap.put("key",-1);
                getMap.put("text","已领取");
                getMap.put(VALUE,"对不起，您不能领取更多优惠券");
                CacheUtil.getCache().setKeyValue(COUPON_GET + couponId + "." + userId, getMap);
            }
        } catch (InterruptedException e) {
            logger.debug(e);
            Thread.currentThread().interrupt();
        } finally {
            //释放一个资源
            semaphore.release(1);
        }

        return resultMap(code,msg);
    }



    public Object getCouponResultUseDetailsChartInfoById(Long couponId) {

        PluginCoupon pc = pluginCouponService.queryById(couponId);

        List<Map<String,Object>> resultList = Lists.newArrayList();
        Map<String,Object> chatMap1 = Maps.newHashMap();
        chatMap1.put("x","卡券总量");
        chatMap1.put("y",pc.getRpcMaxCount());

        EntityWrapper<PluginCouponResult> en = new EntityWrapper<>();
        en.eq(COUPON_ID,couponId);
        Map<String,Object> chatMap2 = Maps.newHashMap();
        chatMap2.put("x","已领取");
        chatMap2.put("y",selectCount(en));

        en.eq("use_status",1);
        Map<String,Object> chatMap3 = Maps.newHashMap();
        chatMap3.put("x","已使用");
        chatMap3.put("y",selectCount(en));

        resultList.add(chatMap1);
        resultList.add(chatMap2);
        resultList.add(chatMap3);

        return resultMap(resultList);
    }

    public Object findCouponsInfoByCouponNum(String couponNum,Long couponId){
        String aliUrl = env.getProperty(OSS_IMG_PATH);
        PluginCouponResult pcr = new PluginCouponResult();
        pcr.setCouponNum(couponNum);
        PluginCouponResult pluginCouponResultSelected =  mapper.selectOne(pcr);
        if(pluginCouponResultSelected.getCouponid().equals(couponId)) {
            Map<String,Object> data = baseMapper.findCouponsInfoByCouponNum(couponNum);
            if(data != null){
                Integer useStatus = (Integer) data.get("useStatus");
                int outTime = 2;
                if( useStatus == 0){
                    data.put(USESTATUS_NAME,"未使用");
                    data.put(USESTATUS_COLOR,"#48dc98");
                }else if(useStatus == 1){
                    data.put(USESTATUS_NAME,"已使用");
                    data.put(USESTATUS_COLOR,"#8d8d8d");
                }else if(useStatus == outTime){
                    data.put(USESTATUS_NAME,"已过期");
                    data.put(USESTATUS_COLOR,"#8d8d8d");
                }
                data.put(HEADIMG_URL,data.get(HEADIMG_URL)==null?"":aliUrl+data.get(HEADIMG_URL));
                return resultMap( data,1,"");
            }else{
                return resultMap(0,"无效二维码");
            }
        } else {
            return resultMap(0,"卡券信息不符，无法核销");
        }

    }

    public Object getCouponStatusInfo(Long couponId,Long userId){

        int code = 1;
        String msg = "";

        PluginCoupon pc = pluginCouponService.queryById(couponId);

        if(pc.getDelStatus() == 1) {
            return resultMap(0,"优惠券已被管理员删除");
        }

        Map<String,Object> dataMap = Maps.newHashMap();

        Object getterCountObj = CacheUtil.getCache().get(COUPON_GETTER_COUNT + couponId);
        int getterCount = 0;

        EntityWrapper<PluginCouponResult> rpce = new EntityWrapper<>();
        rpce.eq("userid",userId);
        rpce.eq(COUPON_ID,couponId);
        List<PluginCouponResult> pcrList = selectList(rpce);

        dataMap.put("MaxCount",pc.getRpcMaxCount());
        dataMap.put("CouLimit",pc.getRpcCouLimit());
        dataMap.put("have",pcrList.size());

        if (getterCountObj != null) {
            getterCount = (int) getterCountObj;
        }

        if (getterCount >= pc.getRpcMaxCount()) {
            return resultMap(dataMap,-1,"已抢光");
        }



        if(pcrList.size() >= pc.getRpcCouLimit()){
            return resultMap(dataMap,2,"您已获取该优惠券");
        }

        return resultMap(dataMap,code,msg);

    }

    public Object getCouponResultForTmp(Long couponId,Long userId){

        Object getMapObj = CacheUtil.getCache().getKeyValue(COUPON_GET + couponId + "." + userId);
        Map<String,Object> getMap = Maps.newHashMap();
        if(getMapObj != null){
            getMap = (Map<String,Object>)getMapObj;
        }else {
            getMap.put("key",0);
            getMap.put("text","排队抢券中");
            getMap.put(VALUE,"正在排队抢券中");

        }
        return resultMap(getMap);
    }


    public Object listPluginCouponResult(Long couponId,Integer useStatus) {
        Page<PluginCouponResultListVO> page = baseMapper.listPluginCouponResult(couponId,useStatus);
        formatPlugCoupon(page);
        return page;
    }


    private void formatPlugCoupon(Page<PluginCouponResultListVO> page){
        String aliUrl = env.getProperty(OSS_IMG_PATH);
        for(PluginCouponResultListVO vo : page.getRecords()){

            switch (vo.getStatus()){
                case 0:
                    vo.setStatusName("未使用");
                    break;
                case 1:
                    vo.setStatusName("已使用");
                    break;
                case 2:
                    vo.setStatusName("已过期");
                    break;
                    default:
            }

            if(vo.getUserHead() != null) {
                vo.setUserHead(FormatPhotoUrlUtil.formatString(aliUrl,vo.getUserHead()));
            }
        }
    }
}
